<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus';
//控制注册与登录表单的显示， 默认非注册，即登录
const isRegister = ref(false)
const registerData = ref({
    username: '',
    password: '',
    rePassword: ''
})


//校验密码的函数
const checkRePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次确认密码'))
    } else if (value !== registerData.value.password) {
        callback(new Error('请确保两次输入的密码一样'))
    } else {
        callback()
    }
}


//定义表单校验规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    rePassword: [
        { validator: checkRePassword, trigger: 'blur', }
    ]
}

import { userRegisterService } from '@/api/user.js'
//调用后台接口完成注册
const register = async () => {
    // registerData是响应式对象，需要.value才能获取值
    let result = await userRegisterService(registerData.value);
    //见request响应拦截器，对失败进行处理了
    // if(result.code===0){
    //     //成功了
    //     alert(result.data?result.data:'注册成功！');
    // }else{
    //     //失败了
    //     alert(result.message+' 注册失败!');
    // }

    ElMessage.success(result.data ? result.data : '注册成功！');
}
import { userLoginService } from '@/api/user.js'
//登录函数
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import useUserInfoStore from '@/stores/userInfo';
const router = useRouter()//得到一个路由器
const tokenStore = useTokenStore();
const login = async () => {
    //调用接口完成登录
    let result = await userLoginService(registerData.value);
    // if(result.code===0){
    //     //成功了
    //     alert(result.data?result.data:'登录成功！');
    // }else{
    //     //失败了
    //     alert(result.message+' 登录失败!');
    // }
    // alert(result.data?result.data:'登录成功！');


    //将token存储到pinia(的store)中
    tokenStore.setToken(result.data);
    const userInfoStore = useUserInfoStore()
    await userInfoStore.renewInfo();
    ElMessage.success(result.message ? result.message : '登录成功！');

    console.log(userInfoStore.info.username);
    //跳转到首页 路由完成跳转
    router.push('/');

}


//在点击注册或返回时添加清空数据的逻辑
const clearData = () => {
    registerData.value.username = '';
    registerData.value.password = '';
    registerData.value.rePassword = '';
}

// 修改点击注册链接的逻辑
const goToRegister = () => {
    isRegister.value = true;
    clearData();
}

// 修改点击返回链接的逻辑
const goBack = () => {
    isRegister.value = false;
    clearData();
}


// ...其他选项
import { onMounted } from 'vue';
onMounted(() => {
    console.log('组件login.vue已挂载');
});
</script>

<template>
    <el-row class="login-page">
        <el-col :span="12" class="bg"></el-col>
        <el-col :span="6" :offset="3" class="form">
            <!-- 注册表单                                                             绑定数据  -->
            <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"
                        :ref="defaultFocus"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item prop="rePassword">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                        v-model="registerData.rePassword" @keyup.enter="register"></el-input>
                </el-form-item>
                <!-- 注册按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="register">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="goBack()">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-else :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>登录</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.password" @keyup.enter="login"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox>记住我</el-checkbox>
                        <el-link type="primary" :underline="false">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="login">
                        <!-- <img src="@/assets/editUser_black.png" alt="icon" class="button-image" /> -->
                        登录
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="goToRegister()">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
    height: 100vh;
    background-color: #fff;

    .bg {
        background:
            // url('@/assets/login.png') no-repeat center right / 10% 10%,
            // url('@/assets/logo_blue2.png') no-repeat center center/40%,
            //  url('@/assets/gdupt.png') no-repeat 5% 5% / 20% auto,
            url('@/assets/login_welcom.png') no-repeat center / cover;
        border-radius: 0 20px 20px 0;
        position: relative;
    }

    //   .bg::after, .gdupt {
    //     /* 应用相同的样式到 .bg::after 和 .gdupt */
    //     content: "冷库状态\A监测与管理\A系统";
    //     position: absolute;
    //     top: 50%;
    //     left: 50%;
    //     transform: translate(-50%, -50%);
    //     color: #fff;
    //     font-size: 2vw;
    //     font-family: 'Arial', sans-serif;
    //     font-weight: bold;
    //     text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
    //     white-space: pre;
    //     text-align: center;
    //     line-height: 1.2;
    //     padding: 10px 20px;
    //     border-radius: 10px;
    //     background: #0e72be80;
    //     box-shadow: 0 0 2vw rgba(239, 239, 239, 0.5);
    //   }
    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>
